//
//  HZGoodsNumPicker.m
//  app
//
//  Created by 刘华舟 on 15/5/4.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZGoodsNumPicker.h"
#import "HDAppDelegate.h"
#import "HZCartTableViewCell.h"
#import "HZCartCellModel.h"

#import "HZRemoteResult.h"

#import "HZBase64Handler.h"
#import "HZMallCartsHttpManager.h"

static const CGFloat kGoodsNumPickerMargin = 40.0f;
static const CGFloat kPickViewCellHeight = 60.0f;
static const CGFloat kPickViewHeight = 360.0f;
static const CGFloat kPickTitleHeight = 80;


static const CGFloat kButtonHeight = 70.0f;
static const CGFloat kButtonWidth = 240.0f;
static const CGFloat kViewPadding = 16.0f;

static const CGFloat kBackViewHeight = kPickTitleHeight+kButtonHeight+2*kViewPadding;


@interface HZGoodsNumPicker()<UIPickerViewDelegate, UIPickerViewDataSource>

@property (assign, nonatomic) NSInteger chosedNum;

@property (strong, nonatomic) UIView *backView;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UIPickerView *pickView;
@property (strong, nonatomic) UIButton *cancelBtn;
@property (strong, nonatomic) UIButton *sureBtn;

@property (strong, nonatomic) HZRemoteResult *deleteResult;
@property (strong, nonatomic) HZRemoteResult *addResult;

@property (strong, nonatomic) HZCartTableViewCell *cell;

@end

@implementation HZGoodsNumPicker

- (instancetype)initWithFrame:(CGRect)frame{
    HDAppDelegate *appDelegate = (HDAppDelegate *)[[UIApplication sharedApplication] delegate];
    frame = appDelegate.window.screen.bounds;
    if(self = [super initWithFrame:frame]){
        self.backgroundColor = HZ_MALL_MASK_BACKGROUND_COLOR;
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureOnView)];
        [self addGestureRecognizer:tapGestureRecognizer];
        
        //初始化backView
        self.backView = [[UIView alloc] initWithFrame:CGRectOf([self.ufo fx:UB_LEFT ux:kGoodsNumPickerMargin fy:UB_CENTER uy:-kBackViewHeight/2], [self.ubo fw:UB_WIDTH uw:-2*kGoodsNumPickerMargin uh:kBackViewHeight])];
        self.backView.backgroundColor = HZ_WHITE_COLOR;
        
        //初始化title
        self.titleLabel = [[UILabel alloc] initWithFrame:CGRectOf([self.backView.ubo fx:UB_LEFT fy:UB_TOP],
                                                                  [self.backView.ubo fw:UB_WIDTH uh:kPickTitleHeight ph:-1])];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        self.titleLabel.font = [UIFont systemFontOfSize:16];
        self.titleLabel.textColor = HZ_MALL_TEXT_BLACK_COLOR;
        self.titleLabel.backgroundColor = HZ_MALL_S_LIGHT_GRAY_BACKGROUND_COLOR;
        self.titleLabel.text = @"修改数量";
        [self.backView addSubview:self.titleLabel];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectOf([self.titleLabel.ubo fx:UB_LEFT fy:UB_BOTTOM],
                                                                  [self.titleLabel.ubo fw:UB_WIDTH ph:1])];
        lineView.backgroundColor = HZ_MALL_SEPARATOR_CELL_LINE;
        [self.backView addSubview:lineView];
        
        //初始化picker
        self.pickView = [[UIPickerView alloc] initWithFrame:CGRectOf([self.backView.ubo fx:UB_LEFT fy:UB_TOP uy:kPickTitleHeight],
                                                                     [self.backView.ubo fw:UB_WIDTH uh:kPickViewHeight])];
        self.pickView.delegate = self;
        self.pickView.dataSource = self;
        self.pickView.showsSelectionIndicator = YES;
        self.pickView.backgroundColor = HZ_MALL_M_LIGHT_GRAY_BACKGROUND_COLOR;
        self.pickView.tintColor = HZ_MALL_MAIN_THEME_ORANGE;
        [self.backView addSubview:self.pickView];
        
        //初始化取消按钮和确定按钮
        self.cancelBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.pickView.ufo fx:UB_1_4 ux:-kButtonWidth/2 fy:UB_BOTTOM uy:kViewPadding], [self.backView.ubo uw:kButtonWidth uh:kButtonHeight])];
        [self.cancelBtn setBackgroundColor:HZ_CLEAR_COLOR];
        [self.cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [self.cancelBtn.titleLabel setFont:JKAppGlobleFontContentText];
        [self.cancelBtn addTarget:self action:@selector(cancelBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
        self.cancelBtn.layer.masksToBounds = YES;
        self.cancelBtn.layer.cornerRadius = [self.ubo uw:8];
        self.cancelBtn.layer.borderColor = HZ_MALL_M_LIGHT_GRAY_BACKGROUND_COLOR.CGColor;
        self.cancelBtn.layer.borderWidth = [self.ubo pw:2];
        [self.cancelBtn setTitleColor:HZ_MALL_TEXT_BLACK_COLOR forState:UIControlStateNormal];
        [self.backView addSubview:self.cancelBtn];
        
        self.sureBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.pickView.ufo fx:UB_3_4 ux:-kButtonWidth/2 fy:UB_BOTTOM uy:kViewPadding], [self.backView.ubo uw:kButtonWidth uh:kButtonHeight])];
        [self.sureBtn setBackgroundColor:HZ_MALL_MAIN_THEME_ORANGE];
        [self.sureBtn.titleLabel setFont:JKAppGlobleFontContentText];
        self.sureBtn.layer.masksToBounds = YES;
        self.sureBtn.layer.cornerRadius = [self.ubo uw:8];
        [self.sureBtn setTitle:@"确定" forState:UIControlStateNormal];
        [self.sureBtn addTarget:self action:@selector(sureBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.backView addSubview:self.sureBtn];
        
        self.allRowsNum = 100;
        self.chosedNum = 1;
        
        self.deleteResult = [HZRemoteResult target:self action:@selector(deleteGoodsFinished)];
        self.addResult = [HZRemoteResult target:self action:@selector(addGoodsFinished)];
        
        [self addSubview:self.backView];
        
        self.backView.frame = CGRectOf([self.ubo fx:UB_LEFT ux:kGoodsNumPickerMargin fy:UB_CENTER uy:-kBackViewHeight/2 oy:-self.pickView.frame.size.height/2], [self.ubo fw:UB_WIDTH uw:-2*kGoodsNumPickerMargin uh:kBackViewHeight oh:self.pickView.frame.size.height]);
    }
    
    return self;
}

- (void)showGoodsNumPickerWithCell:(HZCartTableViewCell *)cell{
    self.cell = cell;
    HZCartCellModel *model = cell.model;
    self.allRowsNum = [model.reserveNum integerValue]>99 ? 99:[model.reserveNum integerValue];
    [self.pickView reloadAllComponents];
    
    
    
    HDAppDelegate *appDelegate = (HDAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.window addSubview:self];
    
    //这里是初始化，自动转一圈，避免第一次是数组第一个值造成留白
    [self.pickView selectRow:self.allRowsNum + [model.goodsCountNum integerValue]-1 inComponent:0 animated:NO];
}

//点击空白处
- (void)tapGestureOnView{
    [self removeFromSuperview];
}

//取消按钮点击
- (void)cancelBtnOnClick{
    HZLog(@"picker取消按钮点击");
    [self removeFromSuperview];
}

//确定按钮点击
- (void)sureBtnOnClick{
    [self removeFromSuperview];
    HZLog(@"picker确定按钮点击");
    self.chosedNum = [self.pickView selectedRowInComponent:0]%self.allRowsNum+1;
    HZCartCellModel *model = self.cell.model;
    
    /** 如果用户登录了，则会向网络加载 -write by khzliu */
    
    if ([self checkUserLongin]) {
        HZMallCartsHttpManager *httpManager = [HZMallCartsHttpManager shareHttpRequestMananger];
        NSString *num = [NSString stringWithFormat:@"%d", abs([model.goodsCountNum integerValue] - self.chosedNum)];
        NSString *goods = [NSString stringWithFormat:@"[{\"act_id\":\"%@\",\"shop_id\":\"%@\",\"product_id\":\"%@\",\"num\":\"%@\",\"gifts\":\"%@\"}]", model.actID, model.shopID, model.goodsID, num, model.giftModel.product_id];
        
        NSDictionary *params = @{APIKEY_mall_goods:[HZBase64Handler encodeBase64WithString:goods]};
        
        if ([model.goodsCountNum integerValue] > self.chosedNum) {
            
            [httpManager deleteGoodsWithParams:params result:self.deleteResult];
        }
        
        if ([model.goodsCountNum integerValue] < self.chosedNum) {
            
            [httpManager addGoodsWithParams:params result:self.deleteResult];
        }

    }
    
    model.goodsCountNum = [NSString stringWithFormat:@"%ld", (long)self.chosedNum];
    if (self.delegate && [self.delegate respondsToSelector:@selector(goodsNumPickerDismissWithCell:)]) {
        [self.delegate goodsNumPickerDismissWithCell:self.cell];
    }
}
//检查用户是否登录
- (BOOL)checkUserLongin{
    NSString *uid = [[NSUserDefaults standardUserDefaults] stringForKey:@"uid"];
    if (uid && uid.length>0) {
        return YES;
    }
    return NO;
}


//返回列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
//返回每列的最大行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return self.allRowsNum*5;
}
//每一列中每一行的具体内容
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [NSString stringWithFormat:@"%ld", (long)(row%self.allRowsNum +1)];
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return UF(kPickViewCellHeight);
}

//选中哪一列哪一行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    self.chosedNum = row%self.allRowsNum + 1;
    NSUInteger max = 0;
    NSUInteger base10 = 0;
    
    if(component == 0)
    {
        max = self.allRowsNum*5;
        base10 = (max/2)-(max/2)%self.allRowsNum;
        [pickerView selectRow:[pickerView selectedRowInComponent:component]%self.allRowsNum+base10 inComponent:component animated:false];
    }
}


#pragma mark HZRemoteResult回调
//完成删除
- (void)deleteGoodsFinished{
    
}

//完成添加
- (void)addGoodsFinished{
    
}

@end
